/**
 * 【题目】给定一个正整数数组nums和一个目标值targets,在数组中找到和为targets的两个正整数的下表
 * 【示例】nums=[2,7,9,13] targets=16 fn(nums,targets) = [1,2]
 */

// 方法1；两次循环

const func01 = (nums, targets) => {
    for (let i = 0; i < nums.length; i += 1) {
        const diff = Math.abs(targets - nums[i])
        for (let j = i + 1; j < nums.length; j += 1) {
            if (diff === nums[j]) {
                return [i, j]
            }
        }
    }
}

console.log(func01([2, 7, 9, 13], 16))

// 方法2: 利用数组的下标和值进行转换位置，一次循环减少时间
const func02 = (nums, targets) => {
    const temps = []
    for (let i = 0; i < nums.length; i += 1) {
        const diff = Math.abs(targets - nums[i])
        if (temps[diff]) return [i, temps[diff]]
        temps[nums[i]] = i
    }
}

console.log(func02([2, 7, 9, 13], 16))
